<?php
App::import('Sanitize');
class UsersController extends AppController {

	var $name = 'Users';

	function index() {
		$this->redirect('/');
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}

	/**
	 *	View User Profile
	 */
	function view($id = null) {
        if (!$id) {
		    $current = $this->Session->read('Auth');
		    if(!empty($current['User'])) {
		    	$this->Session->setFlash(__('User does not exist', true));
				$this->redirect(array('action' => 'index'));
		    } else {
		    	$this->redirect('/');
		    }
		}
	    $this->set('user', $this->User->read(null, $id));
	}

	/**
	 *	Add a new user
	 */
	function add() {
		$this->set('title_for_layout', 'Create an account');
	
		// If user filled the form up
		if (!empty($this->data)) {
		
			// If password and confirmation-password fields match
		    if ($this->data['User']['password'] == $this->Auth->password($this->data['User']['password_confirm'])) {
		    
		    	// sanitize any user-input data
		    	$this->User->data = Sanitize::clean($this->data);
		    	
		    	// Create the user after everything validates
		        $this->User->create();
		        
		        // If registration is successful, redirect to show the Success message
		        if ($this->User->save($this->data)) {
					$this->Session->setFlash(__('Registration Successful', true));
					$this->redirect(array('action' => 'index'));
				}
		        
		        // Else 
		        else {
    				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
		        	$this->data['User']['password'] = null;
		        	$this->data['User']['password_confirm'] = null;
		        }
		    }
		}
	}

	/**
	 *	Login: Contained code works only after autoRedirect is set to false
	 *	in beforeFilter of AppController
	 *
	 *	Code to integrate login with RememberMe component derived from
	 *	http://lecterror.com/articles/view/rememberme-component-the-final-word and
	 *	http://blog.japanesetesting.com/2009/09/11/cakephp-and-rememberme-autologins-for-the-soul/
	 */
	function login() {
			if(!$this->Auth->user()) {
				return;
			}
		
			if(empty($this->data)) {
				if(!$this->Auth->user('oauth_uid')) {
					$this->Session->setFlash(__('You are already logged in, '.$this->Auth->user('name').'!', true));
				} else {
					$this->Session->setFlash(__('You are already logged in via Facebook, '.$this->Auth->user('name').'!', true));
				}
			}
		
			if (empty($this->data['User']['remember_me'])) {
				// remove 'Remember Me' cookie using RememberMe component
				$this->RememberMe->delete();
			} else {
				$this->RememberMe->remember(
					$this->data['User']['username'],
					$this->data['User']['password']
				);
			
				unset($this->data['User']['remember_me']);
			}
			$id = $this->Auth->user('id');
 			$this->redirect(array('controller'=>'users','action'=>'view/'.$id),null,true);
	}
	
	/**
	 *	Login via Facebook using the Graph API
	 */
	function fblogin() {
		// Import Facebook PHP-SDK
		App::import('Vendor', 'facebook');
		$facebook = new Facebook(
			array(
				'appId'		=> '163993313641185',
				'secret'	=> '05625240e8e6aabc7c5d1741613ac719',
				'cookie'	=> true
			)
		);
		
		// Generate Facebook Session
		$session = $facebook->getSession();
		
		// Generate Login URL
		$login_url = $facebook->getLoginUrl(
			array(
				//Requested permissions
				'req_perms' => 'email',
				
				// User is redirected to this URL once authentication is successful 
				'next' => 'http://localhost/cakephp/users/callback'
			)
		);
		
		// If session is available
		if(!empty($session)) {
			$this->Session->write('uid',$session['uid']);
			$this->Session->write('username',$session['name']);
			$this->redirect(array('controller'=>'users','action'=>'index'),null,true);
		} else {
			$this->redirect($login_url);
		}
	}
	
	/**
	 *	Callback once User Authentication
	 *	via Facebook's Graph API is a success
	 */
	function callback() {
		// Import Facebook PHP-SDK
		App::import('Vendor', 'facebook');
		$facebook = new Facebook(
			array(
				'appId'		=> '163993313641185',
				'secret'	=> '05625240e8e6aabc7c5d1741613ac719',
				'cookie'	=> true
			)
		);
		
		// Generate Facebook Session
		$session = $facebook->getSession();
		
		// If session is available
		if(!empty($session)) {
			try{
				// Get user data using the access_token returned by Facebook on callback
				$user=json_decode(file_get_contents('https://graph.facebook.com/me?access_token='.$session['access_token']));
			}
			catch(FacebookApiException $e){
				// Log the error
				error_log($e);
			}
			
			if(!empty($user)) {
				// check user on users table by oauth_uid
				$user_id=$this->User->findByOauthUid($user->id);
				
				// If empty, that means user not found. So create the user!
				if(empty($user_id)){
					$this->data['User']['oauth_provider']='facebook';
					$this->data['User']['oauth_uid']=$user->id;
					$this->data['User']['access_token']=$session['access_token'];
					$this->data['User']['username']=$user->id.strtolower($user->first_name);
					$this->data['User']['password']=sha1($session['access_token']);
					$this->data['User']['email']=$user->email;
					$this->data['User']['name']=$user->name;
					$hashedPasswords = $this->Auth->hashPasswords($this->data);
					if($this->User->save($this->data)){
						// Populate Auth.User data for current Facebook User
						$this->Session->write('Auth',$this->User->findByOauthUid($user->id));
						$this->Session->setFlash(__('Your profile has been saved', true));
					} else {
						$this->Session->setFlash(__('Sorry, we could not save your profile. Please, try again.', true));
					}
				} else {
					// Populate Auth.User data for current Facebook User
					$this->Session->write('Auth',$this->User->findByOauthUid($user_id['User']['oauth_uid']));
				}
			}
		} else {
			$this->Session->setFlash(__('Sorry, we could not authenticate you.', true));
		}
		$id = $this->Auth->user('id');
		$this->redirect(array('controller'=>'users','action'=>'view/'.$id),null,true);
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		} else {
			if($id === $this->Auth->user('id')){
				if (!empty($this->data)) {
					if ($this->User->save($this->data)) {
						$this->Session->setFlash(__('The user has been saved', true));
						$this->redirect(array('action' => 'index'));
					} else {
						$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
					}
				}
				if (empty($this->data)) {
					$this->data = $this->User->read(null, $id);
				}
			} else{
				$this->Session->setFlash(__('You can\'t do that, nutcase!', true));
				$this->redirect(array('controller'=>'users','action'=>'view/'.$this->Auth->user('id')),null,true);
			}
		}
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for user', true));
			$this->redirect(array('action'=>'index'));
		} else {
			if($id === $this->Auth->user('id')) {
				if ($this->User->delete($id)) {
					$this->Session->setFlash(__('User deleted', true));
					$this->redirect(array('action'=>'index'));
				}
			} else {
					$this->Session->setFlash(__('You can\'t do that, nutcase!', true));
					$this->redirect(array('controller'=>'users','action'=>'view/'.$this->Auth->user('id')),null,true);
			}
		}
		$this->Session->setFlash(__('User was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	
	/**
	 *
	 */
	 function logout() {
        $this->RememberMe->delete();
        $this->Session->destroy();
        $this->Session->setFlash('You have successfully logged out.');
        $this->redirect($this->Auth->logout());
     }

}
?>
